<template>
  <ElementDialog
    :close-on-click-modal="false"
    append-to-body
    :visible.sync="visible"
    title="添加责任人"
    top="5%"
    width="50%">
    <ElTable
      ref="deptTable"
      v-loading="loading"
      border
      :data="deptList"
      row-key="id"
      append-to-body
      :default-expand-all="false"
      :tree-props="{ children: 'children' }"
      @selection-change="handleSelectionChange">
      <ElTableColumn type="selection" width="55" />
      <ElTableColumn prop="name" label="部门名称" :show-overflow-tooltip="true" />
      <ElTableColumn prop="code" label="部门编号" align="center" />
      <ElTableColumn prop="weight" label="排序" align="center" />
      <ElTableColumn prop="createTime" label="创建时间" align="center" />
    </ElTable>
    <template #footer>
      <span class="dialog-footer">
        <ElButton @click="closeDialog">关闭</ElButton>
        <ElButton type="primary" @click="checkRowData">确定</ElButton>
      </span>
    </template>
  </ElementDialog>
</template>

<script>
  import { fetchTree } from '@/api/admin/dept'
  import { mapState } from 'vuex'

  export default {
    name: 'Dept',
    props: {
      // 允许选择的条数
      allowChooseNum: {
        type: Number,
        default: 1
      }
    },
    data() {
      return {
        // addOrUpdateVisible: false,
        // 遮罩层
        loading: true,
        // 表格树数据
        deptList: [],
        visible: true,
        multipleSelection: []
      }
    },
    computed: {
      ...mapState('user', ['permissions'])
    },
    created() {
      this.init()
    },
    methods: {
      init() {
        this.visible = true
        this.getList()
      },
      getList() {
        this.loading = true
        fetchTree().then(response => {
          this.deptList = response.data.data

          this.loading = false
        })
        // console.log(this.deptList)
      },
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.deptTable.toggleRowSelection(row)
          })
        } else {
          this.$refs.deptTable.clearSelection()
        }
      },
      handleSelectionChange(val) {
        if (this.allowChooseNum > 0) {
          if (val.length > this.allowChooseNum) {
            this.toggleSelection(val)
            this.$message.success(`只能选择${this.allowChooseNum}条`)
            return
          }
        }
        this.multipleSelection = val
      },
      checkRowData() {
        this.$emit('getDeptData', this.multipleSelection)
        this.visible = false
      },
      closeDialog() {
        this.visible = false
      }
    }
  }
</script>
